export default class SocketServer {
    //
    static instance = null
    static get Instance() {
        if(!this.instance) {
            this.instance = new SocketServer()
        }
        return this.instance
    }

    ws = null
    //存储回调函数
    callBackMapping = {}
    //标识是否连接成功
    connected = false
    //记录重试的次数
    sendRetryCount = 0
    //重新连接尝试的次数
    connectRetryCount = 0

    //定义连接服务器的方法
    connect() {
        if(!window.WebSocket) {
            return console.log('您的浏览器不支持WebSocket');
        }
        this.ws = new WebSocket('ws://localhost:8889')

        //连接成功
        this.ws.onopen = () => {
            console.log('连接服务器成功了');
            this.connected = true
            this.connectRetryCount = 0
        }
        //连接失败
        this.ws.onclose = () => {
            console.log('连接服务器失败');
            this.connected = false
            this.connectRetryCount++
            setTimeout(() => {
                this.connect()
            }, 500 * this.connectRetryCount)
        }
        //得到服务端发送来的数据
        this.ws.onmessage = (msg) => {
            console.log('从服务器获得了数据');
            // console.log(msg.data);
            const recvData = JSON.parse(msg.data)
            const socketType = recvData.socketType
            //判断回调函数是否存在
            if(this.callBackMapping[socketType]) {
                const action = recvData.action
                if(action === 'getData') {
                    const realData = JSON.parse(recvData.data)
                    this.callBackMapping[socketType].call(this, realData)
                } else if(action === 'fullScreen') {
                    this.callBackMapping[socketType].call(this, recvData)
                } else if(action === 'themeChange') {

                }
            }
        }
    }

    //回调函数的注册
    registerCallBack(socketType, callBack) {
        this.callBackMapping[socketType] = callBack
    }

    //取消回调函数
    unRegisterCallBack(socketType) {
        this.callBackMapping[socketType] = null
    }

    //定义数据的方法
    send(data) {
        //判断后没有连接成功
        if(this.connected) {
            this.sendRetryCount = 0
            this.ws.send(JSON.stringify(data))
        } else {
            this.sendRetryCount++
            setTimeout(() => {
                this.send(data)
            }, this.sendRetryCount * 500)
        }
    }
}